package com.lx.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 用拦截器设置登录后才能查看页面
 */
//@WebFilter("/FilterDemo3")
public class FilterDemo3 implements Filter {
    public void init(FilterConfig config) throws ServletException {

    }


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //0. 强制转换
        HttpServletRequest request = (HttpServletRequest) req;
        //1. 获取资源请求路径
        String uri = request.getRequestURI();
        //2. 判断是否包含登录相关资源
        if (uri.contains("/login.jsp") || uri.contains("LoginServlet")){
        chain.doFilter(req, resp);
        }else {
            //3. 不包含，需要验证用户是否登录
            Object user = request.getSession().getAttribute("user");
            if (user!=null){
                //用户登录 放行
                chain.doFilter(req,resp);
            }else {
                //未登录
                request.setAttribute("msg","未登录，请重新登录");
                request.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }
    }

    public void destroy() {
    }

}
